package com.yonyou.gmmc.dealerApp.api.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.marketing.common.dto.maintain.RepairBookParamDto;
import org.marketing.common.dto.maintain.RepairBookTimeDto;
import org.marketing.common.exception.ServiceAppException;
import org.marketing.common.service.rest.RestServiceConstant;
import org.marketing.common.service.rest.RestServiceParamDto;
import org.marketing.common.service.rest.RestServiceResultDto;
import org.marketing.common.service.rest.RestServiceUtil;
import org.marketing.common.service.rest.SystemSecurityUtil;
import org.marketing.common.util.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dexcoder.dal.JdbcDao;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;

@Service
@Transactional
public class RepairBookingService {
	private Logger  logger = Logger.getLogger(RepairBookingService.class);
    private static final String URL_CODE_REPAIR_BOOK_TIME_COMPLEX = "10021002";
    
    @Autowired
    private JdbcDao jdbcDao;
	/**
     * 
    *
    * @author kaihua
    * @ description 使用GET方法获取预约时间(包含工位信息)
    * @date 2016年12月5日
    * @param paramDto
    * @return
    * @throws Exception
     */
    public List<RepairBookTimeDto> getRepairBookTimeComplex(RepairBookParamDto bookParamDto) throws Exception{
        try {
            logger.info("ENTER INTERFACE getRepairBookTimeSimple");
            if (bookParamDto == null) {
                throw new ServiceAppException("PARAMDTO IS NULL");
            }
            if (CommonUtils.isNullOrEmpty(bookParamDto.getSystemId())) {
                throw new ServiceAppException("SYSTEM ID IS NULL");
            }
            if (CommonUtils.isNullOrEmpty(bookParamDto.getDealerCode())) {
                throw new ServiceAppException("DEALER CODE IS NULL");
            }
            if (CommonUtils.isNullOrEmpty(bookParamDto.getBookDate())) {
                throw new ServiceAppException("BOOK DATE IS NULL");
            }
            if (CommonUtils.isNullOrEmpty(bookParamDto.getBookingType())) {
                throw new ServiceAppException("BOOKING TYPE IS NULL");
            }
            
            //获得URL
            String url = this.queryInterfaceurl(bookParamDto.getDealerCode(), URL_CODE_REPAIR_BOOK_TIME_COMPLEX);
            if (url.equals("")) {
                throw new ServiceAppException("接口URL未维护或者查询错误");
            }
            String dmsDealerCode = this.queryDmsDealerCode(bookParamDto.getDealerCode());
            if (dmsDealerCode.equals("")) {
                throw new ServiceAppException("DMS_DEALER_CODE未维护或者查询错误"); 
            }
            bookParamDto.setDealerCode(dmsDealerCode);
            
            
            //头信息参数(放置加密时间戳)
            Map<String, String> headParam = new HashMap<String, String>();
            //对当前的分钟数进行加密，并且置入头信息
            Long thisTimeMinutes = RestServiceUtil.getNowMinute();
            headParam.put(RestServiceConstant.REQUEST_HEADER_TIME_STAMP, SystemSecurityUtil.encrypt(String.valueOf(thisTimeMinutes)));
            
            
            //封装REST参数
            RestServiceParamDto paramDto = new RestServiceParamDto();
            //url
            paramDto.setUrl(url);
            //头信息
            paramDto.setHeadersParams(headParam);
            //GET的参数内容
            Map<String, String> urlParams = new HashMap<String, String>();
            urlParams.put("appCode", bookParamDto.getSystemId());
            urlParams.put("bookingDate", bookParamDto.getBookDate());
            urlParams.put("dealerCode", bookParamDto.getDealerCode());
            urlParams.put("bookingType", bookParamDto.getBookingType());
            paramDto.setUrlParams(urlParams);
            
            //发送消息请求
            RestServiceResultDto responseDto = RestServiceUtil.getMessageFromDms(paramDto);
            
            //对返回的结果进行处理
            if (responseDto.getResultCode() == RestServiceResultDto.SUCCESS) {
                String resultBody = responseDto.getResultBody();
                logger.info("SUCCESS INTERFACE getRepairBookTimeSimple");
                logger.info(resultBody);
                if (!CommonUtils.isNullOrEmpty(resultBody)) {
                    //JSON转为对象
                    ObjectMapper mapper = new ObjectMapper(); 
                    List<RepairBookTimeDto> bookTimeResultList = mapper.readValue(resultBody, new TypeReference<List<RepairBookTimeDto>>(){});
                    return bookTimeResultList;
                }
                //无数据返回空
                return new ArrayList<RepairBookTimeDto>();
            } else {
                logger.info("FAIL INTERFACE getRepairBookTimeSimple");
                logger.info(responseDto.getHttpCode() + responseDto.getResultMsg());
                throw new Exception(responseDto.getHttpCode() + " " + responseDto.getResultMsg());
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
            throw e;
        }
    }
    private String queryDmsDealerCode(String dealerCode) {
        try {
            Map<String,Object> map=jdbcDao.querySingleResultForSql("select dms_dealer_code from tm_dealer where dealer_code = ? ",new Object[]{dealerCode});
            String dmsDealerCode = (String) map.get("dms_dealer_code");
            return dmsDealerCode;
        } catch(Exception e) {
            return "";
        }
    }
    private String queryInterfaceurl(String dealerCode, String businessType) {
        try {
            Map<String,Object> map=jdbcDao.querySingleResultForSql("SELECT URL FROM tr_dealer_dms_info WHERE DEALER_CODE = ? AND BUSINESS_TYPE = '" + businessType + "' ",new Object[]{dealerCode});
            String url = (String) map.get("url");
            return url;
        } catch(Exception e) {
            return "";
        }
    }
}
